package pro.cherish.smartfile.component.schedule;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import pro.cherish.smartfile.component.FileManager;
import pro.cherish.smartfile.component.RedisFileHelper;
import pro.cherish.smartfile.config.websocket.WebSocketSender;
import pro.cherish.smartfile.module.dto.TaskDto;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 创建人：lys
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2020-12-07 lys 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：ScheduleTask
 * @Description 功能说明：
 * <p>
 *
 * </p>
 * **********************************************************************
 * @date 创建日期： 2020-12-07 lys
 */
@Slf4j
@Component
public class ScheduleTaskConfig {

    @Autowired
    private FileManager fileManager;

    @Value("${smart.file.merge.fail.retry.batch.num:10}")
    private Integer batchNum;
    /**
     * websocket连接map
     */
    @Autowired
    private ConcurrentHashMap<String, WebSocketSender> senderMap;

    /**
     * 每隔10分钟可以合并失败的任务
     */
    @Scheduled(fixedDelay = 10 * 60 * 60)
    public void doMergeFailTask() {
        List<TaskDto> taskDtos = RedisFileHelper.getInstance().consumeMergeFailTask(batchNum);
        for (TaskDto taskDto : taskDtos) {
            try {
                log.error("消费失败任务=\n{}", JSON.toJSONString(taskDto));
                fileManager.newMerge(taskDto.getIdentify(), false);
            } catch (Exception e) {
                log.error("定时消费失败任务，还是未成功,taskDto={},不处理了", JSON.toJSONString(taskDto));
                WebSocketSender webSocketSender = senderMap.get(taskDto.getUserId());
                if (webSocketSender != null) {
                    String msg = StrUtil.format("请考虑重新上传文件[{}]", taskDto.getFilename());
                    webSocketSender.sendData(msg);
                }
            }
        }
    }

}
